package com.erp.module.zhiLiang

import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import com.erp.CaptureActivity
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.activity.MainKActivity
import com.erp.bean.ZhiLiangBean
import com.erp.mclass.UnCeHandler
import com.erp.module.zhiLiang.xingJianZhiLiang.XingJianZhiLiangActivity
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.ZhiLiangAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.util.Dialogutil
import com.erp.util.Httputil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.view.PullToRefreshView
import kotlinx.android.synthetic.main.fragment_zhiliang.*
import java.util.*

/**
 * Created by Administrator on 2018/1/31/031.
 * 作者：刘洋
 * 板材质量
 */

class FragmentZhiLiang : BaseKFragment(),ZhiLiangContract.ZhiLiangView,PullToRefreshView.OnFooterRefreshListener, PullToRefreshView.OnHeaderRefreshListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {

    var updatedialog: AlertDialog? = null
    lateinit var adapter: ZhiLiangAdapter
    lateinit var mlist: MutableList<ZhiLiangBean>
    lateinit var P : IZhiLiangP
    var sousuoBean = IZhiLiangP.ZhiLiangSouSuoBean()
    var zhiliangid: MutableList<String> = ArrayList()
    var zhiliangname: MutableList<String> = ArrayList()
    private val f = "FragmentZhiLiang"
    override fun getLayoutId(): Int {
        fragmentname = f
        return R.layout.fragment_zhiliang
    }

    override fun initData() {
        UnCeHandler.buzhou = "initData"
        val listsp = ArrayList<String>()
        listsp.add("全部")
        listsp.add("有问题")
        listsp.add("无问题")
        UnCeHandler.buzhou = "initData2"
        val sadapter = ArrayAdapter(activity, R.layout.lv_sp_tvitem, listsp)
        spWenti.adapter = sadapter
        atWuLiaoLeiBie.setOnClickListener { atWuLiaoLeiBie.showDropDown() }
        UnCeHandler.buzhou = "initData3"
        mlist = ArrayList()
        adapter = ZhiLiangAdapter(mlist, context!!,this)
        lvFragmentZhiliang.adapter = adapter
        UnCeHandler.buzhou = "initData4"
        P = IZhiLiangP(this,context!!,mlist)
        Pull.setheader(true)
        LlXingJian.setOnClickListener(this)
        Pull.setOnFooterRefreshListener(this)
        Pull.setOnHeaderRefreshListener(this)
        lvFragmentZhiliang.onItemClickListener = this
        lvFragmentZhiliang.onItemLongClickListener = this
        UnCeHandler.buzhou = "initData5"
        etQuery.setOnEditorActionListener { _, actionId, _ ->
            var isOK = true
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    updatedialog = Myutil.showupdatedialog(activity, "正在搜索", false)
                    getData()
                }
                else -> isOK = false
            }
            isOK
        }
        UnCeHandler.buzhou = "initData6"
        spWenti.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                when (position) {
                    1 -> sousuoBean.wenti = ""
                    1 -> sousuoBean.wenti = "yes"
                    2 -> sousuoBean.wenti = "no"
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) = Unit
        }
        UnCeHandler.buzhou = "initData7"
        val listtime = ArrayList<String>()
        listtime.add("创建时间")
        listtime.add("发生时间")
        listtime.add("确认处理方式时间")
        listtime.add("确认补板时间")
        UnCeHandler.buzhou = "initData8"
        val adaptertime = ArrayAdapter(activity, R.layout.lv_sp_tvitem, listtime)
        SpZhiliangTime.adapter = adaptertime
        SpZhiliangTime.setSelection(0)
        UnCeHandler.buzhou = "initData9"
        tvStartTime.text = Myutil.getjulidate(-7)
        tvEndTime.text = Myutil.getjulidate(0)
        UnCeHandler.buzhou = "initData10"
        ivScan.setOnClickListener(this)
        tvStartTime.setOnClickListener(this)
        tvEndTime.setOnClickListener(this)
        btGuolv.setOnClickListener(this)
        tvChongzhi.setOnClickListener(this)
        UnCeHandler.buzhou = "initData11"
        P.getWuLiao_DaiMa()
        ivScan.isFocusable = true
        ivScan.isFocusableInTouchMode = true
        ivScan.requestFocus()
        ivScan.requestFocusFromTouch()
        UnCeHandler.buzhou = "initData12"
        P.gainData("ZhiLiang")
        UnCeHandler.buzhou = "initData13"
        Pull.headerRefreshing()
    }

    fun qingkong(){
        if(isFirstLoad){
            return
        }
        Pull.headerRefreshing()
    }

    private fun getData() {
        sousuoBean.sousuo = etQuery.text.toString()
        sousuoBean.startTime = tvStartTime.text.toString()
        sousuoBean.endTime = tvEndTime.text.toString()
        sousuoBean.quhao = etQuhao.text.toString()
        if (zhiliangname.contains(atWuLiaoLeiBie.text.toString())) {
            zhiliangname.indices
                    .filter { zhiliangname[it] == atWuLiaoLeiBie.text.toString() }
                    .forEach { sousuoBean.wuliao = zhiliangid[it] }
        }
        when(SpZhiliangTime.selectedItem.toString()){
            "创建时间" -> {
                sousuoBean.time_category = "mq.ctime"
            }
            "发生时间" -> {
                sousuoBean.time_category = "mq.occurrence_time"
            }
            "确认处理方式时间" -> {
                sousuoBean.time_category = "mq.dispose_time"
            }
            "确认补板时间" -> {
                sousuoBean.time_category = "mq.buban_time"
            }
        }
        P.guolv(sousuoBean)
    }

    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        UnCeHandler.buzhou = "onItemClick"
        zhiLiangBean = mlist[position]
        val intent = Intent(activity, XingJianZhiLiangActivity::class.java)
        intent.putExtra("code", 2)
        startActivityForResult(intent, 3)
    }

    override fun onClick(view: View) {
        UnCeHandler.buzhou = "onClick"
        when (view.id) {
            R.id.ivScan -> PermissionUtils.issaomiao(activity!!, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                    val intent = Intent()
                    var a = activity
                    if(a != null){
                        intent.setClass(a, CaptureActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                        startActivityForResult(intent, 1)
                    }

                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) =
                        Myutil.MyTost("没有权限，无法扫描")
            })
            R.id.tvStartTime -> {
                Dialogutil.showBottoPopupWindow(tvStartTime, "选择开始时间", tvStartTime.text.toString(), activity)
                Myutil.notjianpan(context, ivScan)
            }
            R.id.tvEndTime -> {
                Dialogutil.showBottoPopupWindow(tvEndTime, "选择结束时间", tvEndTime.text.toString(), activity)
                Myutil.notjianpan(context, ivScan)
            }
            R.id.tvChongzhi -> {
                updatedialog = Myutil.showupdatedialog(activity, "正在重置", false)
                sousuoBean= IZhiLiangP.ZhiLiangSouSuoBean()
                spWenti.setSelection(0)
                etQuhao.setText(sousuoBean.quhao)
                etQuery.setText(sousuoBean.sousuo)
                atWuLiaoLeiBie.setText("")
                tvStartTime.text = sousuoBean.startTime
                tvEndTime.text = sousuoBean.endTime
                getData()
            }
            R.id.btGuolv -> {
                updatedialog = Myutil.showupdatedialog(activity, "正在过滤", false)
                getData()
            }
            R.id.LlXingJian -> {
                xingjian()
            }
        }
    }

    fun xingjian() {
        UnCeHandler.buzhou = "xingjian"
        val intent = Intent(activity, XingJianZhiLiangActivity::class.java)
        intent.putExtra("code", 1)
        activity!!.startActivityForResult(intent, 3)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        UnCeHandler.buzhou = "onActivityResult"
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1 -> {
                    val bundle = data.extras
                    sousuoBean.sousuo = bundle?.get("result") as String
                    etQuery.setText(sousuoBean.sousuo)
                    updatedialog = Myutil.showupdatedialog(activity, "正在刷新", false)
                    getData()
                }
                3 -> {
                    val isshuxing = data.getBooleanExtra("isxing", false)
                    if (isshuxing) {
                        updatedialog = Myutil.showupdatedialog(activity, "正在刷新", false)
                        getData()
                    } else {
                        adapter.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
        UnCeHandler.buzhou = "onItemLongClick"
        if(MainKActivity.uid == mlist[position].creator_uid){
            var c = context
            if(c != null){
                val dialog = AlertDialog.Builder(c)
                dialog.setTitle("提示")
                dialog.setMessage("确定要删除     " + mlist[position].mcode + "     这条质量问题?")
                dialog.setPositiveButton("确定") { dialog, which ->
                    updatedialog = Myutil.showupdatedialog(activity, "正在删除", false)
                    Httputil.deleteZhiLiang(context, mlist[position].id, object : OnUserDataInterface {
                        override fun onUserData(data: String) {
                            Myutil.MyTost("删除成功")
                            updatedialog?.dismiss()
                            mlist.removeAt(position)
                            adapter.notifyDataSetChanged()
                        }

                        override fun onNot(throwable: String) {
                            Myutil.MyTost("删除失败")
                            updatedialog?.dismiss()
                        }
                    })
                }
                dialog.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                dialog.show()
            }

        }else{
            var c = context
            if(c != null){
                val dialog = AlertDialog.Builder(c)
                dialog.setTitle("提示")
                dialog.setMessage(mlist[position].mcode + "这条质量问题不是你上传，不能删除")
                dialog.setPositiveButton("确定") { dialog, which -> dialog.dismiss()}
                dialog.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                dialog.show()
            }

        }
        return true
    }
    override fun xialaOk() {
        updatedialog?.dismiss()
        Pull.onHeaderRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun xialaNo() {
        updatedialog?.dismiss()
        Pull.onHeaderRefreshComplete()
    }

    override fun shanglaOk() {
        updatedialog?.dismiss()
        Pull.onFooterRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun shanglaNo() {
        updatedialog?.dismiss()
        Pull.onFooterRefreshComplete()
    }
    override fun gainDataOk() {
        adapter.notifyDataSetChanged()
    }

    override fun onFooterRefresh(view: PullToRefreshView) {
        P.shangla()
    }
    override fun onHeaderRefresh(view: PullToRefreshView) {
        P.xiala()
    }
    companion object {
        var zhiLiangBean = ZhiLiangBean()
    }
    override fun getWuLiao_DaiMaOK(zhiliangid: MutableList<String>, zhiliangname: MutableList<String>) {
        this.zhiliangid=zhiliangid
        this.zhiliangname=zhiliangname
        Log.d("getWuLiao_DaiMaOK",this.zhiliangname.toString())
        val av = ArrayAdapter(activity, android.R.layout.simple_dropdown_item_1line, this.zhiliangname)
        atWuLiaoLeiBie.setAdapter(av)
    }

    override fun getWuLiao_DaiMaNO() {
    }

    override fun shouhuo(id: String) {
        updatedialog = Myutil.showupdatedialog(activity, "正在收货", false)
        P.shouhuo(id)
    }

    override fun shouhuoOk() {
        updatedialog?.dismiss()
        getData()
    }

    override fun shouhuoNo() {
        updatedialog?.dismiss()
    }
}